package cn.edu.gznu.wecampus.core.auth;

import org.jasig.cas.client.authentication.AttributePrincipal;
import org.jasig.cas.client.validation.Assertion;
import org.jasig.cas.client.validation.Cas20ServiceTicketValidator;
import org.jasig.cas.client.validation.TicketValidationException;
import org.jasig.cas.client.validation.TicketValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.edu.gznu.wecampus.core.BusinessException;
import cn.edu.gznu.wecampus.core.utils.JwtUtils;
import cn.edu.gznu.wecampus.core.web.RestResponse;
import cn.edu.gznu.wecampus.core.web.RestResponseElement;
import cn.edu.gznu.wisedu.entity.ldap.Member;
import cn.edu.gznu.wisedu.repository.ldap.MemberRepository;

@RestController
@RequestMapping("/api/cas")
public class CasApi {
	@Autowired
	private MemberRepository memberRepository;
	
	private String casServerUrlPrefix = "http://authserver.gznu.edu.cn/authserver";
	
	@Value("${cas.callback}")
	private String casService;
	
	@RequestMapping("jwt")
	public RestResponse jwt(String ticket) throws TicketValidationException {
		RestResponseElement response = new RestResponseElement();
		TicketValidator ticketValidator = new Cas20ServiceTicketValidator(casServerUrlPrefix);
		Assertion casAssertion = ticketValidator.validate(ticket, casService);
		AttributePrincipal casPrincipal = casAssertion.getPrincipal();
        String userId = casPrincipal.getName();
        Member member = memberRepository.findByXgh(userId);
		if(member != null) {
			String jwtToken = JwtUtils.sign(member.getUid());
			AuthVo vo = new AuthVo();
			vo.setXgh(member.getUid());
			vo.setName(member.getCommonName());
			vo.setJwtToken(jwtToken);
			response.setElement(vo);
			return response;
		}
		throw new BusinessException("未找到匹配用户");
	}
}
